import Qs from 'qs'
import { axios } from '@/utils/request'
// 通用下载方法
export default function download(url, params, filename,headers=null,isBody = false) {	
	return axios.post(url, params, 
	// 	{
	// 	transformRequest: [(params) => {
	// 		return Qs.stringify(params)
	// 	}],
	// 	headers: {
	// 		'Content-Type': 'application/x-www-form-urlencoded'
	// 	},
	// 	responseType: 'blob'
	// }
	isBody ? {
		headers: headers || {
			'Content-Type': 'application/json;charset=UTF-8',
		},
		responseType: 'blob'
	} : {
		transformRequest: [
			(params) => {
				return Qs.stringify(params)
			}
		],
		headers: headers || {
			'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
		},
		responseType: 'blob'
	}
).then((value) => {
		  let data = value.data
		  // 如果返回的结果是json格式，将blob转成json
			if (data.type === 'application/json') {
				//此时返回的data为blob格式
				const file = new FileReader();//读取文件
				file.readAsText(data, 'utf-8');//读取文件，并设置编码格式为utf-8
				//在读取文件操作完成后触发
				file.onload = () => {
					let pbres = JSON.parse(file.result)
					if (pbres.code && pbres.code != 200) {
						this.$message.error(pbres.msg || '未知错误，请联系管理员')
					}
				}
			} else {
				const content = data
				const blob = new Blob([content])
				if ('download' in document.createElement('a')) {
					const elink = document.createElement('a')
					elink.download = filename
					elink.style.display = 'none'
					elink.href = URL.createObjectURL(blob)
					document.body.appendChild(elink)
					elink.click()
					URL.revokeObjectURL(elink.href)
					document.body.removeChild(elink)
				} else {
					navigator.msSaveBlob(blob, filename)
				}
				this.$message.success('导出成功')
			}
	}).catch((r) => {
		console.log(r)
		this.$message.error( ''+r || '未知错误，请联系管理员' )
	})
}
